package com.cloud.wms.ui.sort.detach;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Message;
import android.view.View;
import android.widget.TextView;

import com.annimon.stream.Stream;
import com.cloud.widget.ScanText;
import com.cloud.wms.R;
import com.cloud.wms.base.BaseBarActivity;
import com.cloud.wms.config.IntentKey;
import com.cloud.wms.tools.RxUtils;
import com.cloud.wms.ui.sort.contract.DetachContact;
import com.cloud.wms.ui.sort.entity.DetachBoxBean;
import com.cloud.wms.ui.sort.entity.DetachDetailBean;
import com.cloud.wms.ui.sort.presenter.DetachPresenter;
import com.cloud.wms.widget.dialog.AlertDialogBuilder;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;

/**
 * Created by FC on 2021/3/9.
 * Desc：
 */
public class DetachConfirmActivity extends BaseBarActivity<DetachPresenter> implements DetachContact.View {
    @BindView(R.id.scan_text)
    ScanText scanText;
    @BindView(R.id.tv_batch_code)
    TextView tvBatchCode;
    @BindView(R.id.tv_detach_result)
    TextView tvDetachResult;
    @BindView(R.id.btn_batch_detail)
    TextView btnBatchDetail;
    @BindView(R.id.btn_reset_detach)
    TextView btnResetDetach;
    @BindView(R.id.btn_confirm_detach)
    TextView btnConfirmDetach;
    private List<DetachDetailBean> detailBeanList;
    private ArrayList<DetachBoxBean> boxBeanList;

    @Override
    protected String barTitle() {
        return "二次分拨";
    }

    @Override
    protected int getResId() {
        return R.layout.activity_second_allocation_confirm;
    }

    @Override
    protected void initEvent() {
        initScanText(scanText);
        detailBeanList = (List<DetachDetailBean>) getIntent().getSerializableExtra(IntentKey.OBJECT_KEY);
        boxBeanList = getIntent().getParcelableArrayListExtra(IntentKey.LIST_KEY);
        tvBatchCode.setText(detailBeanList.get(0).getBatchCode());
        tvDetachResult.setText("0");
    }

    @SuppressLint("CheckResult")
    @Override
    protected void onScanHandle(String result, int resultCode) {
        super.onScanHandle(result, resultCode);
        scanText.addHistory(result);
        List<DetachDetailBean> scanDetailList = Stream.of(detailBeanList)
                .filter(bean -> result.equalsIgnoreCase(bean.getBarCode())).toList();
        if (scanDetailList.size() == 0) {
            scanErrorVoice();
            tvDetachResult.setText("错件");
            return;
        } else {
            for (int i = 0; i < detailBeanList.size(); i++) {
                if (result.equalsIgnoreCase(detailBeanList.get(i).getBarCode())
                        && detailBeanList.get(i).getAmount() > detailBeanList.get(i).getSortAmount()) {
                    tvDetachResult.setText(detailBeanList.get(i).getBatchNo() + "号");
                    detailBeanList.get(i).setSortAmount(detailBeanList.get(i).getSortAmount() + 1);
                    break;
                } else if (i == detailBeanList.size() - 1) {
                    errorVoice();
                    tvDetachResult.setText("多件");
                    return;
                }
            }
        }
        boolean isSortComplete = true;
        for (int i = 0; i < detailBeanList.size(); i++) {
            if (detailBeanList.get(i).getAmount() > detailBeanList.get(i).getSortAmount()) {
                isSortComplete = false;
                break;
            }
        }
        if (isSortComplete) {
            error("当前已分拨完成，2s自动分拨确认！");
            Observable.timer(2000, TimeUnit.MILLISECONDS).compose(RxUtils.threadSwitch()).subscribe(aLong
                    -> mPresenter.confirmDetach(String.valueOf(detailBeanList.get(0).getBatchID()), boxBeanList));
        }
    }

    @SuppressLint("CheckResult")
    @Override
    public void onSuccess(Message message) {
        if (message.what == DetachPresenter.CONFIRM_DETACH_SUCCESS) {
            success("分拨确认成功！");
            Observable.timer(500, TimeUnit.MILLISECONDS).subscribe(aLong -> finish());
        }
    }

    @OnClick({R.id.btn_batch_detail, R.id.btn_reset_detach, R.id.btn_confirm_detach})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_batch_detail:
                Intent intent = new Intent(this, DetachDetailActivity.class);
                intent.putExtra(IntentKey.OBJECT_KEY, (Serializable) detailBeanList);
                startActivity(intent);
                break;
            case R.id.btn_reset_detach:
                new AlertDialogBuilder(this)
                        .setTitle("提示")
                        .setMessage("确定全部商品重新分拨吗？")
                        .setPositiveButton("确定", (dialog, which) -> {
                            for (int i = 0; i < detailBeanList.size(); i++) {
                                detailBeanList.get(i).setSortAmount(0);
                            }
                            tvDetachResult.setText("0");
                        })
                        .setNegativeButton("取消", null)
                        .show();
                break;
            case R.id.btn_confirm_detach:
                new AlertDialogBuilder(this)
                        .setTitle("提示")
                        .setMessage("确定全部商品分拨确认吗？")
                        .setPositiveButton("确定", (dialog, which) -> {
                            for (int i = 0; i < detailBeanList.size(); i++) {
                                if (detailBeanList.get(i).getAmount() > detailBeanList.get(i).getSortAmount()) {
                                    info("存在未分拨的商品，请扫描完确认！");
                                    return;
                                }
                            }
                            mPresenter.confirmDetach(String.valueOf(detailBeanList.get(0).getBatchID()), boxBeanList);
                        })
                        .setNegativeButton("取消", null)
                        .show();
                break;
        }
    }

    @Override
    protected void setupComponent() {
        getActivityComponent().inject(this);
    }
}
